const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 确保上传目录存在
const uploadsDir = path.join(__dirname, 'public', 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

// 配置 multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadsDir);
    },
    filename: function (req, file, cb) {
        const uniqueName = uuidv4() + '.html';
        cb(null, uniqueName);
    }
});

const upload = multer({ 
    storage: storage,
    fileFilter: function (req, file, cb) {
        if (file.mimetype === 'text/html' || path.extname(file.originalname).toLowerCase() === '.html') {
            cb(null, true);
        } else {
            cb(new Error('只允许上传HTML文件'));
        }
    }
});

// 路由：首页
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 路由：上传HTML文件
app.post('/upload', upload.single('htmlFile'), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ error: '请选择HTML文件上传' });
    }

    const fileUrl = `/uploads/${req.file.filename}`;
    const fullUrl = `${req.protocol}://${req.get('host')}${fileUrl}`;

    res.json({
        success: true,
        filename: req.file.originalname,
        url: fileUrl,
        fullUrl: fullUrl,
        message: '文件上传成功！'
    });
});

// 路由：获取所有上传的文件列表
app.get('/files', (req, res) => {
    fs.readdir(uploadsDir, (err, files) => {
        if (err) {
            return res.status(500).json({ error: '读取文件列表失败' });
        }

        const fileList = files
            .filter(file => file.endsWith('.html'))
            .map(file => ({
                name: file,
                url: `/uploads/${file}`,
                fullUrl: `${req.protocol}://${req.get('host')}/uploads/${file}`,
                uploadTime: fs.statSync(path.join(uploadsDir, file)).mtime
            }))
            .sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime));

        res.json(fileList);
    });
});

// 错误处理中间件
app.use((error, req, res, next) => {
    if (error instanceof multer.MulterError) {
        if (error.code === 'LIMIT_FILE_SIZE') {
            return res.status(400).json({ error: '文件太大' });
        }
    }
    res.status(400).json({ error: error.message });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log(`上传目录: ${uploadsDir}`);
});
